<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Controller;

use Kcdns\Admin\Common\ModelCfg;

/**
 * 基础功能控制器
 */
class CommonController extends AdminController
{

    // 配置模型名称
    protected $modelName = null;

    // 模型操作名称
    protected $modelAction = '';

    // 表单状态 add / edit
    protected $modelEnv = '';

    // 指定模板
    protected $template = '';

    // 数据过滤条件
    protected $listWhere = [];

    // 新增保存填充数据
    protected $insertSaveData = [];

    // 更新保存填充数据
    protected $updateSaveData = [];

    // 新增显示数据
    protected $insertShowData = [];

    // 新增后跳转 : 1:列表页; 2:刷新当前页; url
    protected $addRedirct = '1';

    // 更新后跳转 : 1:列表页; 2:刷新当前页; url
    protected $editRedirect = '1';

    //回调函数
    protected $callback=false;

    /**
     * 列表
     * 通过 $this->modelName 设定操作的表名
     */
    public function index()
    {
        $cfg = new ModelCfg($this->modelName);
        $modelAction = $this->modelAction ?: 'getList';
        $listData = $cfg->model->$modelAction(array_merge(I('get.'), $this->listWhere));
        $export = I('_export_') ? (I('_export_type_') ?: true) : false;

        $this->assign('cfg', $cfg);
        $this->assign('listData', $listData);
        IS_PJAX || !IS_AJAX ? $this->display($this->_getTpl("Common/index")) : W('datatable/render', compact('listData', 'cfg', 'export'));
    }

    /**
     * 新增记录 表单/保存
     * 通过 $this->modelName 设定操作的表名
     * 通过 $this->addData 设定填充数据
     */
    public function add()
    {
        $cfg = new ModelCfg($this->modelName, $this->modelEnv ?: 'add');
        if (IS_POST) {

            $modelAction = $this->modelAction ?: 'insert';
            $status = $cfg->model->$modelAction(I('post.'), $this->insertSaveData);
            if (is_callable($this->callback)) {
                $status AND call_user_func_array($this->callback, [$status]);
            }
            if($cfg->name == 'goods') {
                //保存sku库存
                OE('goods')->setGoodsSku(I('post.'), $status,1);
            }
            // 保存成功后跳转地址
            switch ($this->addRedirct) {
                case 1:
                    $url = U('index');
                    break;
                case 2:
                    $url = $_SERVER['REQUEST_URI'];
                    break;
                default:
                    $url = $this->addRedirct;
            }
            $status ? $this->success('添加成功', $url) : $this->error('添加失败');
        }
        if($cfg->name == 'goods'){
            $skuarr = $this->getSku2(0);
            $cfg->sku = $skuarr;
        }
        $this->meta_title = '新增';
        $this->assign('data', $this->insertSaveData);
        $this->assign('cfg', $cfg);
        $this->assign('env', 'add');
        $this->display($this->_getTpl('Common/form'));
    }

    public function getSku($a){

        $s = M('sku')->where(['pid'=>0])->select();
        $arr = [];
        $bigskus = [];//规格搭配

        if($s){
            foreach ($s as $k => $v){
                $s2 = M('sku')->where(['pid'=>0,['id'=>['neq',$v['id']]]])->select();

                $bigsku_ids = $v['id'].'-0';
                $bigskuarr = ['ids'=>$bigsku_ids,'names'=>$v['name']];
                if(!in_array($bigskuarr,$bigskus)){

                    array_push($bigskus,$bigskuarr);
                }

                if($s2){
                    foreach ($s2 as $k2 => $v2){
                        $bigsku_ids = $v['id'].'-'.$v2['id'];
                        $bigskuname = $v['name'].'-'.$v2['name'];
                        $bigskuarr = ['ids'=>$bigsku_ids,'names'=>$bigskuname];
                        if(!in_array($bigskuarr,$bigskus)){

                            array_push($bigskus,$bigskuarr);
                        }
                    }
                }
                $ss = M('sku')->where(['pid'=>$v['id']])->select();
                if($ss){
                    foreach ($ss as $kk => $vv){
                        $stock = 0;
                        if($a){
                            $sku_ids = $vv['id'].'-0';

                            $getgoodssku = M('goods_sku')->where(['sku_ids'=>$sku_ids,'goods_id'=>$a])->find();
                            if($getgoodssku){
//                                if($getgoodssku['stock'] >0){
                                    $stock = $getgoodssku['stock'];
                                    $sell_price = $getgoodssku['sell_price'];
                                    $vip_price = $getgoodssku['vip_price'];
                                    $agent_price = $getgoodssku['agent_price'];
//                                }
                                $arr_one = ['id'=>$vv['id'],'pid'=>$vv['pid'],'name'=>$vv['name'],'id2'=>0,'pid2'=>0,'name2'=>'','stock'=>$stock,'price1'=>$sell_price,'price2'=>$vip_price,'price3'=>$agent_price];
                                if(!in_array($arr_one,$arr)){
                                    array_push($arr,$arr_one);
                                }
                            }
                        }



                        $sss = M('sku')->where(['pid'=>['neq',$v['id']]])->select();
                        if($sss){
                            foreach ($sss as $kkk => $vvv){
                                $stock = 0;
                                if($vvv['pid']>0){
                                    if($a){
                                        $sku_ids = $vv['id'].'-'.$vvv['id'];
                                        $getgoodssku = M('goods_sku')->where(['sku_ids'=>$sku_ids,'goods_id'=>$a])->find();
                                    }

                                    if($getgoodssku){
//                                        if($getgoodssku['stock'] >0){
                                        $stock = $getgoodssku['stock'];
                                        $sell_price = $getgoodssku['sell_price'];
                                        $vip_price = $getgoodssku['vip_price'];
                                        $agent_price = $getgoodssku['agent_price'];
//                                    }
                                        $arr_one = ['id'=>$vv['id'],'pid'=>$vv['pid'],'name'=>$vv['name'],'id2'=>$vvv['id'],'pid2'=>$vvv['pid'],'name2'=>$vvv['name'],'stock'=>$stock,'price1'=>$sell_price,'price2'=>$vip_price,'price3'=>$agent_price];
                                        if(!in_array($arr_one,$arr)){
                                            array_push($arr,$arr_one);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return [$bigskus,$arr];
    }


    public function getSku2($a){

        $s = M('sku')->where(['pid'=>0])->select();
        $arr = [];
        $bigskus = [];//规格搭配

        if($s){
            foreach ($s as $k => $v){
                $s2 = M('sku')->where(['pid'=>0,['id'=>['neq',$v['id']]]])->select();

                $bigsku_ids = $v['id'].'-0';
                $bigskuarr = ['ids'=>$bigsku_ids,'names'=>$v['name']];
                if(!in_array($bigskuarr,$bigskus)){

                    array_push($bigskus,$bigskuarr);
                }

                if($s2){
                    foreach ($s2 as $k2 => $v2){
                        $bigsku_ids = $v['id'].'-'.$v2['id'];
                        $bigskuname = $v['name'].'-'.$v2['name'];
                        $bigskuarr = ['ids'=>$bigsku_ids,'names'=>$bigskuname];
                        if(!in_array($bigskuarr,$bigskus)){

                            array_push($bigskus,$bigskuarr);
                        }
                    }
                }
                $ss = M('sku')->where(['pid'=>$v['id']])->select();
                if($ss){
                    foreach ($ss as $kk => $vv){
                        $stock = 0;
                        if($a){
                            $sku_ids = $vv['id'].'-0';

                            $getgoodssku = M('goods_sku')->where(['sku_ids'=>$sku_ids,'goods_id'=>$a])->find();
                        }
                        if($getgoodssku['stock'] >0){
                            $stock = $getgoodssku['stock'];
                            $sell_price = $getgoodssku['sell_price'];
                            $vip_price = $getgoodssku['vip_price'];
                            $agent_price = $getgoodssku['agent_price'];
                        }
                        $arr_one = ['id'=>$vv['id'],'pid'=>$vv['pid'],'name'=>$vv['name'],'id2'=>0,'pid2'=>0,'name2'=>'','stock'=>$stock,'price1'=>$sell_price,'price2'=>$vip_price,'price3'=>$agent_price];
                        if(!in_array($arr_one,$arr)){
                            array_push($arr,$arr_one);
                        }
                        $sss = M('sku')->where(['pid'=>['neq',$v['id']]])->select();
                        if($sss){
                            foreach ($sss as $kkk => $vvv){
                                $stock = 0;
                                if($vvv['pid']>0){
                                    if($a){
                                        $sku_ids = $vv['id'].'-'.$vvv['id'];
                                        $getgoodssku = M('goods_sku')->where(['sku_ids'=>$sku_ids,'goods_id'=>$a])->find();
                                    }

                                    if($getgoodssku['stock'] >0){
                                        $stock = $getgoodssku['stock'];
                                        $sell_price = $getgoodssku['sell_price'];
                                        $vip_price = $getgoodssku['vip_price'];
                                        $agent_price = $getgoodssku['agent_price'];
                                    }
                                    $arr_one = ['id'=>$vv['id'],'pid'=>$vv['pid'],'name'=>$vv['name'],'id2'=>$vvv['id'],'pid2'=>$vvv['pid'],'name2'=>$vvv['name'],'stock'=>$stock,'price1'=>$sell_price,'price2'=>$vip_price,'price3'=>$agent_price];
                                    if(!in_array($arr_one,$arr)){
                                        array_push($arr,$arr_one);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return [$bigskus,$arr];
    }

    /**
     * 编辑记录 表单/保存
     * 通过 $this->modelName 设定操作的表名
     */
    public function edit()
    {
        $cfg = new ModelCfg($this->modelName, $this->modelEnv ?: 'edit');

        if (IS_POST) {
            // 使用 get 中的主键值覆盖 post 中的主键值
            // get 参数经过签名处理, 可以防止通过表单篡改主键
            $modelAction = $this->modelAction ?: 'update';
            $status = $cfg->model->$modelAction(I('post.'), array_merge(I('get.') ?: [], $this->updateSaveData));
            if (is_callable($this->callback)) {
                $status AND call_user_func_array($this->callback, [$status]);
            }
            if($cfg->name == 'goods') {
                //保存sku库存
                OE('goods')->setGoodsSku(I('post.'), I('get.goods.id'),2);
            }
            // 保存成功后跳转地址
            switch ($this->editRedirect) {
                case 1:
                    $url = U('index');
                    break;
                case 2:
                    $url = $_SERVER['REQUEST_URI'];
                    break;
                default:
                    $url = $this->editRedirect;
            }
            $status ? $this->success('保存成功', $url) : $this->error('保存失败');
        }

        $modelAction = $this->modelAction ?: 'getData';
        $data = $cfg->model->$modelAction(I('get.'), $this->listWhere);

        if($cfg->name == 'goods'){
            $a = I('get.goods.id');
            $skuarr = $this->getSku($a);
            $cfg->sku = $skuarr;
        }


        $this->meta_title = '编辑';
        $this->assign('data', array_merge($data, $this->insertShowData));
        $this->assign('cfg', $cfg);
        $this->assign('env', 'edit');
        $this->display($this->_getTpl('Common/form'));
    }

    /**
     * 查看记录
     * 通过 $this->modelName 设定操作的表名
     */
    public function view()
    {
        if (IS_POST) {
            $this->error('不可修改');
        }

        $cfg = new ModelCfg($this->modelName, $this->modelEnv ?: 'view');
        $modelAction = $this->modelAction ?: 'getData';
        $data = $cfg->model->$modelAction(I('get.'), $this->listWhere);

        $this->meta_title = '详情';
        $this->assign('data', $data);
        $this->assign('cfg', $cfg);
        $this->assign('env', 'view');
        $this->display($this->_getTpl('Common/form'));
    }

    //二维码
    public function qrcode()
    {
        $cfg = new ModelCfg($this->modelName, $this->modelEnv ?: 'view');
        $modelAction = $this->modelAction ?: 'getData';
        $data = $cfg->model->$modelAction(I('get.'), $this->listWhere);

        $url = OE('util')->qrcode($data[$cfg->table.'.'.$field=I('get.field','id')]?:"$field 没有值");
        list($width, $height) = getimagesize('.'.$url);
        echo "<table width='100%'><tr><td align='center'><img style='margin:55px 0 5px 0;width:" . $width . "px;height:" . $height . "px' src='{$url}'></td></tr></table>";
    }

    /**
     * 默认删除操作
     * 所有数据只能通过id删除
     * 通过 $this->modelName 设定操作的表名
     */
    public function del()
    {
        $cfg = new ModelCfg($this->modelName);
        $modelAction = $this->modelAction ?: 'del';
        $status = $cfg->model->$modelAction($this->_getIds(), $this->listWhere);
        $status ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 用于变更字段值
     * get 中包含变更数据的主键和需要变更的字段/值
     * 通过 $this->modelName 设定操作的表名
     */
    public function set()
    {
        $cfg = new ModelCfg($this->modelName);
        $modelAction = $this->modelAction ?: 'set';
        $status = $cfg->model->$modelAction($this->_getIds(), I('get.'), $this->listWhere);
        $status ? $this->success('操作成功') : $this->error('操作失败');
    }

    public function __call($method, $args)
    {
        // 将 index123 替换为 index, 为一个 action 提供多个入口
        $actionName = preg_replace("/([a-zA-Z0-9_][a-zA-Z_]+)(\d*)$/", "$1", $method);
        if ($actionName == $method) {
            E('404');
        }
        $this->$actionName();
    }

    /**
     * 获取定制模板
     */
    protected function _getTpl($defaultTpl)
    {
        $tpl = $this->template ?: CONTROLLER_NAME . '/' . ACTION_NAME;
        return file_exists_case($this->view->parseTemplate($tpl)) ? $tpl : $defaultTpl;
    }

    /**
     * 获取批量/异步操作中的id列表
     */
    protected function _getIds()
    {
        $ids = I('ids', 0);
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $ids = array_unique($ids) or $this->error('请选择要操作的数据!');
        return $ids;
    }
}
